from decimal import Decimal

from lxml import etree
from util.selenium.webdriver.common.by import By


# from base.base_method import bm
# from util.db_operate import SaveData, GetTechList
from spider_data.spiderBaseMethod import bm
from util.g import g
# from util.handle_list import bm.get_first, bm.join_and_repalce
# from util.handle_rd import handle_rd_data

def get_content(driver=None):
    try:
        # for i, pn in enumerate(page_objs, 1):
        WriteRDForm = list()
        i: int = 1
        while True:
            # # # 判断是第一个元素时不需要点击。
            if i == 1:
                bm.wait(driver=driver, ele_loc=g.table_loc)
            # if i != 1:
            #     page_objs = bm.get_page_num(driver=driver)
            #     page_objs[i - 1].click()

            #     # # # TODO 这里调用每个页面的解析数据方法， 。
            records_loc = (By.CSS_SELECTOR, 'tbody.tableBody tr')
            text = driver.page_source
            tree = etree.HTML(text)
            records = tree.xpath("//tbody[@class='tableBody']/tr")
            # records = driver.find_elements(*records_loc)

            # print(pn.find_element)
            # print(dir(pn.find_element))
            # pn_loc = (By.CSS_SELECTOR, g.page_css + f':nth-of-type({i})')

            for index, r in enumerate(records, 1):

                # # TODO 这里选择最后一个元素进行点击， 然后进行解析数据。
                operate_btn_loc = (By.CSS_SELECTOR, f'tbody.tableBody tr:nth-of-type({index}) td:last-child a')
                # # # nth-last-child 不好用
                # print(operate_btn_loc)
                if g.full_verify is True:
                    bm.wait(driver=driver, ele_loc=operate_btn_loc)
                    # # # TODO 这里不能直接使用自动化工具进行点击。
                    # click_detail_js = f'document.querySelector("tbody.tableBody tr:nth-of-type({index}) td:last-child a").click()'
                    driver.find_element(*operate_btn_loc).click()
                    bm.wait(driver=driver, ele_loc=g.title_loc)
                    # # # TODO 进行点击操作后， 解析数据的方法 。方法中需要解析数据， 点击返回列表按钮。
                    text = driver.page_source

                    rd_info = parse_and_save(driver=driver, text=text)
                    WriteRDForm.append(rd_info)
                    # if i != 1 and index != 1:
                    if i != 1:
                        # 跳转到第 i 页
                        show_last_page_btn_loc = (By.CSS_SELECTOR, ".pagination.pull-right li:nth-of-type(3) a:nth-of-type(5)")
                        start_page = 5
                        while True:
                            # if i > start_page:
                            #     bm.click(driver=driver, ele_loc=show_last_page_btn_loc)
                            if i > start_page:
                                start_page += 2
                                bm.click(driver=driver, ele_loc=show_last_page_btn_loc)
                            else:
                                aim_page = (By.XPATH, """//ul[@class='pagination pull-right']/li[3]/a[text() = '{}']""".format(i))
                                bm.click(driver=driver, ele_loc=aim_page)
                                break

                        bm.wait(driver=driver, ele_loc=g.table_loc)
                else:
                    # TODO 解析表格数据
                    rd_item = dict()
                    rd_id =bm.get_ids(r.xpath("./td[2]/text()"))
                    rd_item["rd_id"] = rd_id

                    rd_name = bm.get_first(r.xpath("./td[3]/text()"))
                    rd_item["rd_name"] = rd_name

                    tech_fieldname = bm.handle_domain(r.xpath("./td[4]/text()"))
                    rd_item["tech_fieldname"] = tech_fieldname

                    tech_source = bm.get_first(r.xpath("./td[5]/text()"))
                    rd_item["tech_source"] = tech_source

                    ipr_ids = bm.get_ids(r.xpath("./td[6]/text()"))
                    rd_item["ipr_ids"] = ipr_ids

                    start_end_date = bm.handle_rd_date(r.xpath("./td[7]/text()"))
                    rd_item["start_date"], rd_item["end_date"] = start_end_date

                    rd_spendtotal = bm.get_float_str(r.xpath("./td[8]/text()"))
                    rd_item["rd_spendtotal"] = rd_spendtotal
                    WriteRDForm.append(rd_item)

            # 跳转到下一页
            next_btn = bm.get_ele(driver=driver, ele_loc=g.next_btn_loc)
            onclick = None
            try:
                onclick = next_btn.get_attribute("onclick")
            except Exception as err:
                g.logger.error("get next page button\' attribute error: {}".format(err))
            if onclick is None:
                # driver.switch_to.default_content()
                break
            else:
                bm.click(driver=driver, ele_loc=g.next_btn_loc)
                bm.wait(driver=driver, ele_loc=g.table_loc)
                i += 1
        return {"key": "WriteRDForm", "value": WriteRDForm}
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)

def parse_and_save(driver=None, text=None):
    try:
        text = text.replace('<div class="line"></div>', '')
        tree = etree.HTML(text)
        rd_item = dict()

        rd_id_name = bm.join_and_repalce(tree.xpath('//input[@id="hcod"]/@value'))
        rd_item['rd_id'] = bm.get_ids(id_str=rd_id_name)

        # rd_base = bm.get_first(tree.xpath('//div[@class="box-body"]/div[1]'))

        rd_name = bm.get_first(tree.xpath('//input[@id="yproductName"]/@value'))
        rd_item['rd_name'] = rd_name
        # domain = bm.handle_domain(domain=rd_base.xpath('./div[1]/div[2]//small/text()'))
        # print(domain)
        domain1 = bm.get_first(li=tree.xpath("//div[@id='uniform-onemain']/span/text()"))
        domain2 = bm.get_first(li=tree.xpath("//div[@id='uniform-scdmain']/span/text()"))
        domain3 = bm.get_first(li=tree.xpath("//div[@id='uniform-thdmain']/span/text()"))
        # # # 处理技术领域信息
        rd_item['tech_fieldname'] = ",".join([domain1, domain2, domain3])

        start_date = bm.str_to_date(s=tree.xpath("//input[@id='dataEprPQzsj']/@value"))
        end_date = bm.str_to_date(s=tree.xpath("//input[@id='dataEprPJssj']/@value"))
        rd_item["start_date"] = start_date
        rd_item["end_date"] = end_date

        tech_source_name = bm.get_first(tree.xpath('//input[@id="uniform-jslyList"]/@value'))
        rd_item['tech_source'] = tech_source_name

        # # # 技术来源为字典值， 需要在 sys_dict 表中获取 value
        ipr_ids = bm.get_first(tree.xpath('//textarea[@id="yxPZscqbha"]/text()'))
        rd_item['ipr_ids'] = bm.get_ids(id_str=ipr_ids)

        # rd_expenditure = bm.get_first(tree.xpath('//div[@class="box-body"]/div[2]/div[@class="right-p"]'))

        rd_budget = bm.get_float_str(bm.get_first(tree.xpath("//input[@id='spending']/@value")))
        rd_item['rd_budget'] = rd_budget
        rd_spendtotal = bm.get_float_str(bm.get_first(tree.xpath("//input[@id='yfjfzzc']/@value")))
        rd_item['rd_spendtotal'] = rd_spendtotal
        rd_spend1styear = bm.get_float_str(bm.get_first(tree.xpath("//input[@id='zc3']/@value")))
        rd_item['rd_spend1styear'] = rd_spend1styear
        rd_spend2ndyear = bm.get_float_str(bm.get_first(tree.xpath("//input[@id='zc2']/@value")))
        rd_item['rd_spend2ndyear'] = rd_spend2ndyear
        rd_spend3rdyear = bm.get_float_str(bm.get_first(tree.xpath("//input[@id='zc1']/@value")))
        rd_item['rd_spend3rdyear'] = rd_spend3rdyear

        ooim = tree.xpath('//textarea[@id="PLxmd"]/@value')
        rd_item['ooim'] = bm.handel_long_text(ooim)
        cti = tree.xpath('//textarea[@id="PHxjs"]/@value')
        rd_item['cti'] = bm.handel_long_text(cti)
        pra = tree.xpath('//textarea[@id="PQdcg"]/@value')
        rd_item['pra'] = bm.handel_long_text(pra)

        # # # TODO 这里调用 SaveData 模块将数据保存到 ent_res_rd 表 中。
        # print(f'\n{rd_item}\n')
        # SaveData().save(table='ent_res_rd', value=rd_item)



        # # #  点击返回列表按钮。
        back_list_loc = (By.CSS_SELECTOR, 'h2.text-center a.left-b')
        bm.wait(driver=driver, ele_loc=back_list_loc)
        driver.find_element(*back_list_loc).click()
        return rd_item
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)


def parse_rd(driver=None):
    try:
        rd_loc = (By.LINK_TEXT, '企业研究开发活动情况表')
        bm.detail_switch_iframe(driver=driver)
        bm.wait(driver=driver, ele_loc=rd_loc)

        driver.find_element(*rd_loc).click()

        bm.wait(driver=driver, ele_loc=g.title_loc)

        # page_objs = bm.get_page_num(driver=driver)
        # # #  获取每一条信息数据的源码， 解析处理数据并存入数据库。
        get_content(driver=driver)
    except Exception as err:
        msg = "error: {} file: {} lines: {}".format(err, err.__traceback__.tb_frame.f_globals["__file__"],
                                                    err.__traceback__.tb_lineno)
        g.logger.error(msg)
        raise Exception(msg)
